import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.*;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName: ExcelUtils
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2020/2/1 14:35
 */
public class ExcelUtils {

    /**
     * 设置个表头吧
     */
    private static final List<String> HEAD_STRING_LIST = Arrays.asList("文件名称", "文件内容");

    /**
     * 把数据写入到excel表格中，写入文件系统
     * @param myFileList    数据列表
     * @param filePath      文件路径
     * @throws IOException  IO异常
     */
    public static void writeExcel(List<MyFile> myFileList, String filePath) throws IOException {
        File file = new File(filePath);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));

        Workbook workbook = new SXSSFWorkbook();

        Sheet sheet = setTitle(workbook);

        int rowNum = 1;
        double size = myFileList.size();
        for (MyFile myFile:myFileList) {
            Row row = sheet.createRow(rowNum++);
            setContent(row, myFile);
            double v = (rowNum - 1) / size * 100;
            System.out.println("表格内容写入已完成" + String.format("%.2f", v) + "%");
        }
        System.out.println("开始写入文件系统");
        workbook.write(bos);
    }

    /**
     * 写入单元格内容
     * @param row       要写入的行
     * @param myFile    要写入的数据对象
     */
    private static void setContent(Row row, MyFile myFile) {
        int cellNum = 0;
        Cell cell;
        cell = row.createCell(cellNum++);
        cell.setCellValue(myFile.getFileName());

        for (String content:myFile.getContents()) {
            cell = row.createCell(cellNum++);
            cell.setCellValue(content);
        }
    }

    /**
     * 写入标题
     * @param workbook  写入的工作空间对象
     * @return  返回当前工作表
     */
    public static Sheet setTitle(Workbook workbook) {
        Sheet sheet = workbook.createSheet();

        // 设置默认行高
        sheet.setDefaultRowHeight((short) 400);
        CellStyle cellStyle = buildHeadCellStyle(sheet.getWorkbook());
        Row head = sheet.createRow(0);
        for (int i = 0;i < HEAD_STRING_LIST.size();i++) {
            Cell cell = head.createCell(i);
            cell.setCellValue(HEAD_STRING_LIST.get(i));
            cell.setCellStyle(cellStyle);
        }
        return sheet;
    }

    /**
     * 设置第一行列头的样式
     * @param workbook 工作簿对象
     * @return 单元格样式对象
     */
    private static CellStyle buildHeadCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        //对齐方式设置
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置背景颜色
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //粗体字设置
        Font font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        return style;
    }

}
